﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace CSharpHelpers.Sockets
{
    public delegate void UserWorkEventHandler<T>(object sender, SocketMessageQueue<T>.EnqueueEventArgs e);

    /// <summary>
    /// Socket消息队列
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class SocketMessageQueue<T>
    {
        /// <summary>
        /// 是否单线程
        /// </summary>
        private bool isOneThread = true;

        /// <summary>
        /// 对isWorking的同步对象   
        /// </summary>
        private object lockIsWorking = new object();

        /// <summary>
        /// 实际的队列
        /// </summary>
        private Queue<T> queue;

        /// <summary>
        /// 队列同步对象
        /// </summary>
        private readonly object lockObj = new object();

        /// <summary>        
        /// 绑定用户需要对队列中的item对象, 施加操作的事件        
        /// </summary>       
        public event UserWorkEventHandler<T> UserWork;

        private Thread m_Thread;

        public SocketMessageQueue()
        {
            queue = new Queue<T>();

            m_Thread = new Thread(new ThreadStart(HandleMessage));
            m_Thread.IsBackground = true;
            m_Thread.Name = "SocketMessageQueueThread";
        }

        public SocketMessageQueue(int n)
        {
            queue = new Queue<T>(n);
        }

        /// <summary>
        /// 开始线程
        /// </summary>
        public void StartThread()
        {
            if (m_Thread != null && m_Thread.ThreadState == (ThreadState.Background | ThreadState.Unstarted))
            {
                m_Thread.Start();
            }
        }

        /// <summary>
        /// 结束线程
        /// </summary>
        public void StopThread()
        {
            if (m_Thread != null)
            {
                m_Thread.Abort();
                m_Thread = null;
            }
        }

        /// <summary>
        /// 接受数据
        /// </summary>
        public void HandleMessage()
        {
            while (true)
            {
                try
                {
                    lock (lockIsWorking)
                    {
                        if (queue.Count > 0)
                        {
                            lock (lockObj)
                            {
                                T item = queue.Dequeue();

                                if (UserWork != null)
                                {
                                    UserWork(this, new EnqueueEventArgs(item));
                                }
                            }
                        }
                    }
                }
                catch
                { }

                Thread.Sleep(20);
            }

        }

        /// <summary>        
        /// 谨慎使用此函数，        
        /// 只保证此瞬间，队列值为空        
        /// </summary>        
        /// <returns></returns>        
        public bool IsEmpty()
        {
            lock (lockObj)
            {
                return queue.Count == 0;
            }
        }

        /// <summary>       
        /// 队列处理是否需要单线程顺序执行        
        /// ture表示单线程处理队列的T对象        
        /// 默认为true，表明按照顺序出队， 单线程处理item       
        ///  *****注意不要频繁改变此项****        
        /// </summary>        
        public bool WorkSequential
        {
            get
            {
                return isOneThread;
            }
            set
            {
                isOneThread = value;
            }
        }

        /// <summary>        
        /// 向工作队列添加对象，        
        /// 对象添加以后，如果已经绑定工作的事件        
        /// 会触发事件处理程序，对item对象进行处理        
        /// </summary>        
        /// <param name="item">添加到队列的对象</param>        
        public void Enqueue(T item)
        {
            lock (lockObj)
            {
                queue.Enqueue(item);
            }
        }


        /// <summary>        
        /// UserWork事件的参数，包含item对象       
        /// </summary>        
        public class EnqueueEventArgs : EventArgs
        {
            public T Item { get; private set; }
            public EnqueueEventArgs(object item)
            {
                try
                {
                    Item = (T)item;
                }
                catch (Exception)
                {
                    throw new InvalidCastException("object to T failed.");
                }
            }
        }
    }
}
